package org.example.springboot_demo1.controllerRequest.cookie_session;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:38917
 * Date:2025/4/8
 * Time:19:02
 */

@RequestMapping("/Cookie_Session")
@RestController
public class Cookie_Session {
    //获取Cookie方式一
    @RequestMapping("/getCookie1")
    public String getCookie1(HttpServletRequest request) {
        //获取到所有的Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Arrays.stream(cookies).forEach(cookie ->
                    System.out.println(cookie.getName() + " : " + cookie.getValue()));
        }else {
            return "Cookie为空";
        }
        return "获取Cookie成功";
    }
    //获取Cookie方式二
    @RequestMapping("/getCookie2")
    //获取到key对应的Cookie
    //这里是获取到key=name的Cookie
    public String getCookie2(@CookieValue("name") String name) {
        System.out.println(name);
        return name;
    }



    //设置Session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        //从Cookie中获取到SessionID,再根据SessionID找到对应的Session,如果没有Session,就会先创建一个Session
        HttpSession session = request.getSession();
        session.setAttribute("name","九转苍翎");
        return "设置Session成功";
    }
    //获取Session方式一
    @RequestMapping("/getSession1")
    public String getSession1(HttpServletRequest request) {
        //从Cookie中获取到SessionID,再根据SessionID找到对应的Session
        HttpSession session = request.getSession();
        //从Session中获取name
        String name = (String) session.getAttribute("name");
        return "从Session中获取 name : "+name;
    }
    //获取Session方式二
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        String name = (String) session.getAttribute("name");
        return "从Session中获取 name : "+name;
    }
    //获取Session方式三
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("name") String name) {
        return "从Session中获取 name : "+name;
    }
}
